using System;
using UnityEngine;

[Serializable]
[RequireComponent(typeof(Rigidbody))]
public class ObjectDrag : MonoBehaviour
{
	public int normalCollisionCount;

	public float moveLimit;

	public float collisionMoveFactor;

	public float addHeightWhenClicked;

	public bool freezeRotationOnDrag;

	public Camera cam;

	private Rigidbody myRigidbody;

	private Transform myTransform;

	private bool canMove;

	private float yPos;

	private bool gravitySetting;

	private bool freezeRotationSetting;

	private float sqrMoveLimit;

	private int collisionCount;

	private Transform camTransform;

	public ObjectDrag()
	{
		normalCollisionCount = 1;
		moveLimit = 0.5f;
		collisionMoveFactor = 0.01f;
		freezeRotationOnDrag = true;
	}

	public void Start()
	{
		myRigidbody = GetComponent<Rigidbody>();
		myTransform = transform;
		if (!cam)
		{
			cam = Camera.main;
		}
		if (!cam)
		{
			UnityEngine.Debug.LogError("Can't find camera tagged MainCamera");
			return;
		}
		camTransform = cam.transform;
		sqrMoveLimit = moveLimit * moveLimit;
	}

	public void OnMouseDown()
	{
		canMove = true;
		myTransform.Translate(Vector3.up * addHeightWhenClicked);
		gravitySetting = myRigidbody.useGravity;
		freezeRotationSetting = myRigidbody.freezeRotation;
		myRigidbody.useGravity = false;
		myRigidbody.freezeRotation = freezeRotationOnDrag;
		Vector3 position = myTransform.position;
		yPos = position.y;
	}

	public void OnMouseUp()
	{
		canMove = false;
		myRigidbody.useGravity = gravitySetting;
		myRigidbody.freezeRotation = freezeRotationSetting;
		if (!myRigidbody.useGravity)
		{
			float y = yPos - addHeightWhenClicked;
			Vector3 position = myTransform.position;
			position.y = y;
			Vector3 vector2 = myTransform.position = position;
		}
	}

	public void OnCollisionEnter()
	{
		collisionCount++;
	}

	public void OnCollisionExit()
	{
		collisionCount--;
	}

	public void FixedUpdate()
	{
		if (canMove)
		{
			myRigidbody.velocity = Vector3.zero;
			myRigidbody.angularVelocity = Vector3.zero;
			float y = yPos;
			Vector3 position = myTransform.position;
			position.y = y;
			Vector3 vector2 = myTransform.position = position;
			Vector3 mousePosition = UnityEngine.Input.mousePosition;
			Camera camera = cam;
			float x = mousePosition.x;
			float y2 = mousePosition.y;
			Vector3 position2 = camTransform.position;
			float y3 = position2.y;
			Vector3 position3 = myTransform.position;
			Vector3 b = camera.ScreenToWorldPoint(new Vector3(x, y2, y3 - position3.y)) - myTransform.position;
			b.y = 0f;
			if (collisionCount > normalCollisionCount)
			{
				b = b.normalized * collisionMoveFactor;
			}
			else if (!(b.sqrMagnitude <= sqrMoveLimit))
			{
				b = b.normalized * moveLimit;
			}
			myRigidbody.MovePosition(myRigidbody.position + b);
		}
	}

	public void Main()
	{
	}
}
